package com.myzk.example.web.filter;

import com.myzk.example.utils.common.IpUtils;
import com.myzk.example.utils.common.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = {"/*"})
@Order(1)
public class RequestLoggingFilter extends OncePerRequestFilter {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        String queryString = request.getQueryString();
        String clientIp = IpUtils.getClientIp(request);
        String userAgent = request.getHeader("User-Agent");
        if(StringUtil.isEmpty(queryString)){
            logger.info("[{}] {} clientIp:[{}] userAgent:[{}]",method,requestURI,clientIp,userAgent);
        }else{
            logger.info("[{}] {}?{} clientIp:[{}] userAgent:[{}]",method,requestURI,queryString,clientIp,userAgent);
        }
        filterChain.doFilter(request,response);
    }
}
